#include "BlockGroup.h"

//////////////////////////////////////////////////////////////////////
//
//		Constructor/Destructor section
//
//////////////////////////////////////////////////////////////////////

BlockGroup::BlockGroup(QObject *parent) :
	QObject(parent),
	groupNumber_( 0 ),
	totalBlocks_( 0 ),
	totalINodes_( 0 ),
	freeBlocks_( 0 ),
	freeINodes_( 0 )
{}

BlockGroup::BlockGroup(const int& number, const int& totalBlocks, const int& totalINodes, QObject *parent) :
	QObject(parent),
	groupNumber_( number ),
	totalBlocks_( totalBlocks ),
	totalINodes_( totalINodes ),
	freeBlocks_( 0 ),
	freeINodes_( 0 )
{}

//////////////////////////////////////////////////////////////////////
//
//		File operations section
//
//////////////////////////////////////////////////////////////////////

int BlockGroup::getGroupOffset() {
	return totalBlocks_ * groupNumber_ * FileSystem::getInstance().getBlockSize();
}

void BlockGroup::readBlockDescriptor( QFile* fs ) {
	//Calculates a descriptor position in The File
	qint64 descriptor_offset = 2048+(getGroupNumber()*32);
	//Reads the data required
	fs->seek(descriptor_offset+0);
	fs->read(reinterpret_cast<char*>(&blockBitmap_), 4);
	fs->seek(descriptor_offset+4);
	fs->read(reinterpret_cast<char*>(&iNodeBitmap_), 4);
}

void  BlockGroup::readBlockStructure( QFile* fs ) {
	qint64 map_offset = FileSystem::getInstance().getBlockSize() * blockBitmap_;
	fs->seek( map_offset );

	int free_blocks = 0;

	for(int i = 0; i< totalBlocks_/8; i++) //XXX: chyba tyle razy! :P
	{
		char c;
		fs->read(&c, 1);
		for(int j = 0; j<8; j++)
		{
			if(!(c & 0x1))
			{
                            free_blocks++;
                        }
			c >>= 1;
		}
	}

	freeBlocks_ = free_blocks;
}

void  BlockGroup::readINodeStructure( QFile* fs ) {
	qint64 map_offset = FileSystem::getInstance().getBlockSize() * iNodeBitmap_;
	fs->seek( map_offset );

	int free_nodes = 0;

	for(int i = 0; i< totalINodes_ /8; i++)
	{
		char c;
		fs->read(&c, 1);
		for(int j = 0; j<8; j++)
		{
			if(!(c & 0x1))
			{
				free_nodes++;
			}
			c >>= 1;
		}
	}

	freeINodes_ = free_nodes;
}
